#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>

int abort_exp = 0;

struct timeval start;
struct timeval end;

double time_diff(struct timeval *start, struct timeval *end){
    return (end->tv_sec - start->tv_sec) + 1e-6*(end->tv_usec - start->tv_usec);
}

double fake_exposure_new(double exp_t){

    uint32_t sleep_cnt_max = (uint32_t)exp_t;
    uint32_t sleep_cnt = 0;
    float usec_f = exp_t - sleep_cnt_max;
    uint32_t usleep_cnt = (uint32_t)(usec_f*1e6);

    gettimeofday(&start, NULL);
    usleep(usleep_cnt);

    while(1){
        if( sleep_cnt >= sleep_cnt_max || abort_exp == 1){
            break;
        }
        sleep_cnt++;
        sleep(1);
    }
    
    gettimeofday(&end, NULL);
    return time_diff(&start,&end);
}

double fake_exposure_old(double exp_t){

    uint32_t sleep_cnt_max = (uint32_t)(exp_t*1e3);
    uint32_t sleep_cnt = 0;

    gettimeofday(&start, NULL);

    while(1){
        if( sleep_cnt >= sleep_cnt_max || abort_exp == 1){
            break;
        }
        sleep_cnt++;
        usleep(1000);
    }
    
    gettimeofday(&end, NULL);
    return time_diff(&start,&end);
}

/*double fake_exposure(double exp_t){*/


/*    if( exp_t < 10 ){*/
/*        gettimeofday(&start, NULL);*/
/*        usleep((uint32_t)(exp_t*1e6));*/
/*        gettimeofday(&end, NULL);*/
/*    }else{*/

/*        gettimeofday(&start, NULL);*/

/*        double t0 = exp_t - (((uint32_t)(exp_t)) / 10)*10;*/

/*        uint32_t sleep_cnt_max = (uint32_t)(exp_t) / 10;*/
/*        uint32_t sleep_cnt = 0;*/

/*        usleep( (uint32_t)(t0*1e6) );*/

/*        while(1){*/
/*            if( sleep_cnt >= sleep_cnt_max ){*/
/*                break;*/
/*            }*/
/*            sleep_cnt++;*/
/*            sleep(10);*/
/*        }*/

/*        gettimeofday(&end, NULL);*/
/*    }*/


/*    return time_diff(&start,&end);*/
/*}*/

int main(int argc, char *argv[] ){

    double exp_t = atof(argv[1]);

    double t_diff_new = fake_exposure_new(exp_t);
    double t_diff_old = fake_exposure_old(exp_t);

    gettimeofday(&start, NULL);
    gettimeofday(&end, NULL);
    
    double t_diff0 = time_diff(&start,&end);

    // printf(" actual time: %f seconds\n", time_diff(&start,&end));
    printf("%10.6f %10.6f %10.6f %10.6f\n", exp_t, t_diff_new, t_diff_old, t_diff0);

    return 0;
}
